package ca.paulshin.yunatube.http.unused;

import static ca.paulshin.yunatube.database.YuNaTubeSqliteDatabase.getInstance;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import ca.paulshin.yunatube.R;
import ca.paulshin.yunatube.YunaTubeApplication;
import ca.paulshin.yunatube.common.Constants;
import ca.paulshin.yunatube.common.Preference;
import ca.paulshin.yunatube.common.Utils;
import ca.paulshin.yunatube.database.YuNaTubeSqliteDatabase;
import ca.paulshin.yunatube.http.YouTubeDataLoader;

public class YouTubeDataLoader2 extends YunaTubeHttpClient2 {
	private static YouTubeDataLoader loader = null;
	public static final int numOfMessages = YunaTubeApplication.debuggable ? 10 : 50;
	
	public static YouTubeDataLoader getLoaderInstance() {
		if (loader == null)
			loader = new YouTubeDataLoader();
		return loader;
	}
	
	public synchronized boolean loadXML() {
		int rand = (int)(Math.random() * 1000000);
		final String xmlURL = Utils.getString(YunaTubeApplication.debuggable ? R.string.test_xml_url : R.string.xml_url) + "?dummy=" + rand;
		Preference.put(YuNaTubeSqliteDatabase.IS_DB_AVAILABLE, false);
		InputStream in = null;
		
		try {
			HttpResponse response = get(xmlURL, null, null);
			in = response.getEntity().getContent();
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(in);
			
			// Load youtube
			NodeList mcats = doc.getElementsByTagName("maincateg");
			
			for (int i = 0; i < mcats.getLength(); i++) {
				String mcat_type = mcats.item(i).getAttributes().getNamedItem("type").getNodeValue();
				String mcat_note = mcats.item(i).getAttributes().getNamedItem("note").getNodeValue();
				
				Element mcatElement = ((Element)mcats.item(i));
				NodeList cats = mcatElement.getElementsByTagName("category");
				for (int j = 0; j < cats.getLength(); j++) {
					String cat_type = cats.item(j).getAttributes().getNamedItem("title").getNodeValue();
					String cat_note = cats.item(j).getAttributes().getNamedItem("note").getNodeValue();
					
					Element catElement = ((Element)cats.item(j));
					NodeList clips = catElement.getElementsByTagName("clip");
					
					for (int k = 0; k < clips.getLength(); k++) {
						String clip_title = clips.item(k).getAttributes().getNamedItem("title").getNodeValue();
						String clip_url = clips.item(k).getAttributes().getNamedItem("url").getNodeValue();
						boolean clip_isNew = clips.item(k).getAttributes().getNamedItem("isNew").getNodeValue().equals("0");
						String clip_note = clips.item(k).getAttributes().getNamedItem("note").getNodeValue();
						
						if (clip_note.equals("")) {
//								if (clip_isNew) {
//									getInstance().insertEntity(TableNew.table, cat_type, clip_title, clip_url);
//								}
//								else {
								getInstance().insertEntity(mcat_type, cat_type, clip_title, clip_url);
//								}
						}
					}
				}
			}
			in.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			Preference.put(YuNaTubeSqliteDatabase.IS_DB_AVAILABLE, true);
		}
	}
	
	public synchronized int loadXMLVersion(String url) {
		InputStream in = null;
		
		try {
			HttpResponse response = get(url, null, null);
			in = response.getEntity().getContent();
		
			// counter
			new DefaultHttpClient().execute(new HttpGet(Constants.YOUNATUBE_COUNTER_URL));
						
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line != null && !line.equals(""))
					sb.append(line);
			}

			// return val from server
			String jsonString = sb.toString();
			JSONObject versionObj = (JSONObject)(JSONValue.parse(jsonString));
			String version = (String)(versionObj.get("version"));
			
			in.close();
			return Integer.parseInt(version);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public synchronized List<String> loadNotices() {
		final String url = Utils.getString(YunaTubeApplication.debuggable ? R.string.test_notices_url : R.string.notices_url);
		
		List<String> noticesList;
		
		InputStream in = null;
		
		try {
			HttpResponse response = get(url, null, null);
			in = response.getEntity().getContent();
		
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line != null && !line.equals(""))
					sb.append(line);
			}

			// return val from server
			String jsonString = sb.toString();
			JSONObject noticesObj = (JSONObject)(JSONValue.parse(jsonString));
			String version = (String)(noticesObj.get("version"));
			JSONArray notices = (JSONArray)(noticesObj.get("notices"));
			
			noticesList = new ArrayList<String>();
			noticesList.add(version);
			for (Object notice : notices) { 
				Object titleObj = ((JSONObject)notice).get("title");
				String title = (String)titleObj;
				noticesList.add(title);
			}
			
			in.close();
			return noticesList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public synchronized String loadFact() {
		final String url = Utils.getString(R.string.yunafact_url);
		
		InputStream in = null;
		
		try {
			HttpResponse response = get(url, null, null);
			in = response.getEntity().getContent();
		
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line != null && !line.equals(""))
					sb.append(line);
			}

			// return val from server
			String jsonString = sb.toString();
			JSONObject factObj = (JSONObject)(JSONValue.parse(jsonString));
			String fact = (String)(factObj.get("fact"));
			fact = fact.replace("&lt;", "<").replace("&gt;",">").replace("&amp;", "&");
			
			in.close();
			return fact;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public synchronized List<String[]> loadMessages(List<String[]> messagesList, List<NameValuePair> params) {
		String url = Constants.TO_YUNA_RETRIEVE;
//		List<String[]> messagesList;
		
		InputStream in = null;
		
		try {
			HttpResponse response = get(url, null, params);
			in = response.getEntity().getContent();
		
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line != null && !line.equals(""))
					sb.append(line);
			}

			// return val from server
			String jsonString = sb.toString();
			
			Utils.debug("!!~!" + jsonString);
			JSONArray messages = (JSONArray)(JSONValue.parse(jsonString));
//			messagesList = new ArrayList<String[]>();
			
			for (Object message : messages) { 
				Object _report = ((JSONObject)message).get("report");
				String report = (String)_report;
				if (Integer.parseInt(report) > Constants.TO_YUNA_REPORT_FILTER) {
					continue;
				}
				Object _id = ((JSONObject)message).get("id");
				String id = (String)_id;
				Object _username = ((JSONObject)message).get("username");
				String username = (String)_username;
				Object _message = ((JSONObject)message).get("message");
				String msg = (String)_message;
				Object _time = ((JSONObject)message).get("time");
				String time = (String)_time;
				Object _device = ((JSONObject)message).get("device");
				String device = (String)_device;
				messagesList.add(new String[]{id, username, msg, time, device, report});
			}

			in.close();
			return messagesList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
	}
	
	//TODO
	public synchronized Boolean sendMessage(String[]params) {
		String user;
		String message;
		try {
			user = URLEncoder.encode(params[0], "utf-8");
			message = URLEncoder.encode(params[1], "utf-8");
		} catch (UnsupportedEncodingException e) {
			return false;
		}
		
		String url = Constants.TO_YUNA_SUBMIT + "?username=" + user + "&message=" + message + "&time=" + params[2] + "&device=" + params[3] +"&report=0";
		
//		Util.debug("url : " + url);
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		HttpResponse response;
		try {
			response = client.execute(request);
			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line != null && !line.equals(""))
					sb.append(line);
			}

			// return val from server
			String jsonString = sb.toString();
			return jsonString.equals("success");
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return false;
	}
	
	public synchronized List<String[]> loadComments(List<String[]> commentsList, List<NameValuePair> params) {
		String url = Constants.YOUTUBE_COMMENT_RETRIEVE;
//		List<String[]> messagesList;
		
		InputStream in = null;
		
		try {
			HttpResponse response = get(url, null, params);
			in = response.getEntity().getContent();
		
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line != null && !line.equals(""))
					sb.append(line);
			}

			// return val from server
			String jsonString = sb.toString();
			JSONArray messages = (JSONArray)(JSONValue.parse(jsonString));
//			messagesList = new ArrayList<String[]>();
			
			for (Object message : messages) { 
				Object _report = ((JSONObject)message).get("report");
				String report = (String)_report;
				if (Integer.parseInt(report) > Constants.TO_YUNA_REPORT_FILTER) {
					continue;
				}
				Object _id = ((JSONObject)message).get("id");
				String id = (String)_id;
				Object _username = ((JSONObject)message).get("username");
				String username = (String)_username;
				Object _message = ((JSONObject)message).get("message");
				String msg = (String)_message;
				Object _time = ((JSONObject)message).get("time");
				String time = (String)_time;
				Object _device = ((JSONObject)message).get("device");
				String device = (String)_device;
				Object _isfirst = ((JSONObject)message).get("isfirst");
				String isfirst = (String)_isfirst;
				commentsList.add(new String[]{id, username, msg, time, device, report, isfirst});
			}

			in.close();
			return commentsList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	//TODO
	public synchronized Boolean sendComment(String[]params) {
		String user;
		String message;
		try {
			user = URLEncoder.encode(params[1], "utf-8");
			message = URLEncoder.encode(params[2], "utf-8");
		} catch (UnsupportedEncodingException e) {
			return false;
		}
		
		String url = Constants.YOUTUBE_COMMENT_SUBMIT + "?ytid=" + params[0] + "&username=" + user + "&message=" + message + "&time=" + params[3] + "&device=" + params[4] +"&report=0";
		
		Utils.debug("url : " + url);
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		HttpResponse response;
		try {
			response = client.execute(request);
			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line != null && !line.equals(""))
					sb.append(line);
			}

			// return val from server
			String jsonString = sb.toString();
			return jsonString.equals("success");
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return false;
	}
}